package com.example.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.example.util.TimeUtil;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value = "/")
public class imageController {

    @Value("${dataPath}")
    String dataPath;

    static Map<String, String> contentType = new HashMap<String, String>() {
        {
            put("jpg", "jpeg");
            put("tiff", "tiff");
            put("gif", "gif");
            put("jfif", "jpeg");
            put("png", "png");
            put("tif", "tiff");
            put("ico", "x-icon");
            put("jpeg", "jpeg");
            put("wbmp", "vnd.wap.wbmp");
            put("fax", "fax");
            put("net", "pnetvue");
            put("jpe", "jpeg");
            put("rp", "vnd.rn-realpix");
        }
    };

    final static Logger log = LoggerFactory.getLogger(imageController.class);

    @RequestMapping(value = "image/upload.do", method = RequestMethod.POST)
    @ResponseBody
    public String uploadMap(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file,
            HttpServletRequest request) {
        Map<String, Object> json = new HashMap<String, Object>();
        int success = 0;
        String msg = "";

        if (file.isEmpty()) {
            log.info("empty file");
            msg = "empty file";
            json.put("success", success);
            json.put("message", msg);
            String result = JSON.toJSONString(json);
            return result;
        } else {
            log.info("===================image upload=====================");
            log.info("size: " + file.getSize());
            log.info("type: " + file.getContentType());
            log.info("name: " + file.getName());
            log.info("originalName: " + file.getOriginalFilename());
            log.info("========================================");
        }
        String trueFileName = file.getOriginalFilename();
        String curTime = TimeUtil.getCurrentTime().replace(" ", "_");
        curTime = curTime.replace(":", "-");
        String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));
        String fileName = trueFileName.split("\\.")[0].replace(" ", "_") + "_" + curTime + suffix;

        String imagePath = dataPath + "/images";
        File imageFolder = new File(imagePath);
        if (!imageFolder.exists()) {
            imageFolder.mkdirs();
        }
        File targetFile = new File(imagePath, fileName);
        log.info("file: " + imagePath + '/' + fileName);

        // 保存
        try {
            // 这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的
            FileUtils.copyInputStreamToFile(file.getInputStream(), targetFile);

        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            log.error("save image faile");
            msg = "save image faile";
            json.put("success", success);
            json.put("message", msg);
            String result = JSON.toJSONString(json);
            return result;
        }

        success = 1;
        msg = "upload  success!";

        json.put("url", "image/" + fileName);
        json.put("success", success);
        json.put("message", msg);
        String result = JSON.toJSONString(json);
        return result;

    }

    /**
     * @description 流的方式得到图片
     * @param request
     * @param httpResponse
     */
    @RequestMapping(value = "image/**", method = RequestMethod.GET)
    public void getMapPic1(HttpServletRequest request, HttpServletResponse httpResponse) {
        String url = request.getRequestURI();
        String filename = url.substring(url.lastIndexOf('/'));
        String suffix = filename.substring(filename.lastIndexOf(".")).toLowerCase();

        String imagePath = dataPath + "/images";
        String filePath = imagePath + '/' + filename;
        log.info("filePath:" + filePath);
        File file = new File(filePath);
        FileInputStream fis = null;
        try {
            String type = "jpeg";
            if (contentType.containsKey(suffix))
                type = contentType.get(suffix);
            httpResponse.setContentType("image/" + type);
            OutputStream out = httpResponse.getOutputStream();
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];

            fis.read(b);
            out.write(b);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
